package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.entity.BtyContractDetail;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDoubleCard;
import cn.stylefeng.guns.sys.modular.system.entity.BtySzgl;
import cn.stylefeng.guns.sys.modular.system.mapper.AreaMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDoubleCardMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDoubleCardParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyContractResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDoubleCardResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyDoubleCardService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import groovy.util.logging.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 双证审核 服务实现类
 * </p>
 *
 * @author liuy
 * @since 2022-06-02
 */
@Service
@Slf4j
public class BtyDoubleCardServiceImpl extends ServiceImpl<BtyDoubleCardMapper, BtyDoubleCard> implements BtyDoubleCardService {
    @Resource
    private AreaMapper areaMapper;
    @Override
    public void add(BtyDoubleCardParam param){
        BtyDoubleCard entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyDoubleCardParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyDoubleCardParam param){
        BtyDoubleCard oldEntity = getOldEntity(param);
        BtyDoubleCard newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        int status=newEntity.getStatus();
        int proId=newEntity.getProId();
        if(status==4){
            List<BtyDoubleCardResult>list=baseMapper.taskList(proId);
            if(ToolUtil.isNotEmpty(list)&&list.size()>0){
                for (BtyDoubleCardResult taskResult : list) {
                    int taskId=taskResult.getTaskId();
                    //营业执照图片
                    if(taskId==11){
                        newEntity.setBusinessLicensePic(taskResult.getContent());
                    }
                    //营业执照名称
                    if(taskId==56){
                        newEntity.setBusinessLicense(taskResult.getContent());
                    }
                    //统一社会信用代码
                    if(taskId==57){
                        newEntity.setSocialCreditCode(taskResult.getContent());
                    }
                    //营业执照地址
                    if(taskId==55){
                        newEntity.setBusinessLicenseAddress(taskResult.getContent());
                    }
                    //法人姓名
                    if(taskId==47){
                        newEntity.setFrxm(taskResult.getContent());
                    }
                    //法人身份证
                    if(taskId==42){
                        newEntity.setFrsfz(taskResult.getContent());
                    }
                    //卫生许可证
                    if(taskId==13){
                        newEntity.setFoodBusinessLicensePic(taskResult.getContent());
                    }
                    //卫生许可证年审日期
                    if(taskId==44){
                        newEntity.setFoodBusinessLicenseDate(taskResult.getContent());
                    }
                }
            }
            newEntity.setStatus(2);
            newEntity.setRejectReason(null);
            newEntity.setUpdateTime(new Date());
        }
        this.updateById(newEntity);
    }

    @Override
    public BtyDoubleCardResult findBySpec(BtyDoubleCardParam param){
        return null;
    }

    @Override
    public List<BtyDoubleCardResult> findListBySpec(BtyDoubleCardParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyDoubleCardParam param){

        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<Map> yyjlList() {
        List<Map> list = areaMapper.yyjlList();
        for (Map map : list) {
            if (map.get("yyjl").equals("孙课=姚翠芳")){
                map.put("yyjl", "孙课");
            }
        }
        return list;
    }

    @Override
    public List<Map> ddList(String yyjl) {
        if(yyjl.equals("孙课")){
           yyjl="孙课=姚翠芳";
        }
        return areaMapper.ddList(yyjl);
    }

    @Override
    public List<BtyDoubleCardResult> openidList(Long id) {
        return baseMapper.openidList(id);
    }

    @Override
    public List<BtyDoubleCardResult> msgList() {
        return baseMapper.msgList();
    }

    @Override
    public ResponseEntity<byte[]> exportMx(HttpServletRequest request, HttpServletResponse response, BtyDoubleCardParam param) {
        try {
            String timestamp=DateUtil.getStampNow();
            String fileName ="双证审核"+timestamp;
            List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
            String username=LoginContextHolder.getContext().getUser().getName();
            List<BtyDoubleCardResult>list=baseMapper.customList(param);
            InputStream stream = exportHandler(list, fileName);
            return new BaseFrontController().buildResponseEntity(stream, fileName + ".xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error("导出明细异常：{}", e.getMessage());
        }
        return null;
    }

    private InputStream exportHandler(List<BtyDoubleCardResult>list ,String name){
        //log.info("exportHandler start...");

        ByteArrayOutputStream out=null;
        InputStream is=null;

        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        //报表样式
        CellStyle contentStyle = ExcelFormatUtil.contentStyle(wb);

        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = 13;

        //SXSSFRow row1 = sheet.createRow(0);
        //row1.setHeight((short)600);
        //SXSSFCell cell0 = row1.createCell(0);
        //sheet.addMergedRegion(new CellRangeAddress(0,0,0,lastCol-1));
//        cell0.setCellValue(name);
//        cell0.setCellStyle(ExcelFormatUtil.titleSytle(wb));

        //设置内容标题
        int contentTitleStartRow = 1;
        String[] titles=new String[]{"序号","工程店名","妖码","营运经理/电话","督导/电话","法人姓名","食品经营许可证截止日期","营业执照名称","统一社会信用代码","营业执照地址","提交时间","通过/驳回时间","状态"};
        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] withs = new int[]{2500, 5000, 5000, 5000, 5000, 5200, 5000, 5000, 5000,5000,5000,5000,5000};
        // 设置报表头样式,cell样式
        CellStyle headSytle = ExcelFormatUtil.headSytle(wb);
        ExcelFormatUtil.initContentTitleEX(sheet,headSytle,contentTitleStartRow,titles,withs);


        int contentStartRow = 2;

        for(int i=0;i<list.size();i++){
            BtyDoubleCardResult mx=list.get(i);
            SXSSFRow row = sheet.createRow(contentStartRow+i-1);
            int j=0;
            SXSSFCell xh = row.createCell(j++);//xuhao
            xh.setCellStyle(contentStyle);
            xh.setCellValue(i+1);

            SXSSFCell cell = row.createCell(j++);//工程店名
            cell.setCellValue(mx.getGcdm()!=null?mx.getGcdm():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//妖码
            cell.setCellValue(mx.getYaoma()!=null?mx.getYaoma():"");
            cell.setCellStyle(contentStyle);

            String yyjlTel=mx.getYyjlTel()!=null?mx.getYyjlTel():"";
            String yyjl=mx.getYyjl()!=null?mx.getYyjl():"";
            String yyjls="";
            if(ToolUtil.isNotEmpty(yyjl)){
                yyjls=yyjl+"/"+yyjlTel;
            }else{
                yyjls=yyjlTel;
            }


            String ddTel=mx.getDdTel()!=null?mx.getDdTel():"";
            String dd=mx.getDd()!=null?mx.getDd():"";
            String dds="";
            if(ToolUtil.isNotEmpty(dd)){
                dds=dd+"/"+ddTel;
            }else{
                dds=ddTel;
            }

            cell = row.createCell(j++);//营运经理/电话
            cell.setCellValue(yyjls);
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//督导/电话
            cell.setCellValue(dds);
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//法人姓名
            cell.setCellValue(mx.getFrxm()!=null?mx.getFrxm():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//食品经营许可证截止日期
            cell.setCellValue(mx.getFoodBusinessLicenseDate()==null?"":mx.getFoodBusinessLicenseDate());
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//营业执照名称
            cell.setCellValue(mx.getBusinessLicense()!=null?mx.getBusinessLicense():"");
            cell.setCellStyle(contentStyle);

            //"营业执照地址","提交时间","通过/驳回时间","状态"

            cell = row.createCell(j++);//统一社会信用代码
            cell.setCellValue(mx.getSocialCreditCode()!=null?mx.getSocialCreditCode():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//营业执照地址
            cell.setCellValue(mx.getBusinessLicenseAddress()!=null?mx.getBusinessLicenseAddress():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//提交时间
            cell.setCellValue(mx.getCreateTime()!=null?DateUtil.getDate(mx.getCreateTime()):"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//通过/驳回时间
            cell.setCellValue(mx.getUpdateTime()!=null?DateUtil.getDate(mx.getUpdateTime()):"");
            cell.setCellStyle(contentStyle);

            // 1未提交 2待审核 3已通过 4已驳回
            int status=mx.getStatus();
            String statusName="";
            if(status==1){
                statusName="未提交";
            }
            if(status==2){
                statusName="待审核";
            }
            if(status==3){
                statusName="已通过";
            }
            if(status==4){
                statusName="已驳回";
            }

            cell = row.createCell(j++);//状态
            cell.setCellValue(statusName);
            cell.setCellStyle(contentStyle);
        }

        try {
            out = new ByteArrayOutputStream();
            wb.write(out);
            is=new ByteArrayInputStream(out.toByteArray());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out!=null){
                    out.close();
                }
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return is;
    }

    /**
     * 批量下载图片
     * @param ids
     * @param request
     * @param response
     */
    @Override
    public void btnDown(String ids, HttpServletRequest request, HttpServletResponse response) {
        try {
            String id[] = ids.split(",");
            //查图片
            List<BtyDoubleCard> pics = this.baseMapper.selectPic(id);

            //多个图片下载地址
            File fileMemu = new File("D:/szsh/sztp/");//输入要删除文件目录的绝对路径
            deleteFile(fileMemu);

            //多个图片下载地址
            for (int i = 0; i < pics.size(); i++) {

                //营业执照
                if (ToolUtil.isNotEmpty(pics.get(i).getBusinessLicensePic())){
                    String yyzz = pics.get(i).getBusinessLicensePic();
                    if (!yyzz.contains("http")){
                        yyzz = "https://rs.bantianyaozg.com" + yyzz;
                        //yyzz = "http://127.0.0.1:88" + yyzz;
                    }
                    if (yyzz.contains(" ")){
                        yyzz = yyzz.replaceAll(" ", "%20");
                    }
                    //根据图片地址构建URL
                    URL url = new URL(yyzz);//营业执照
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();

                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/szsh/sztp/" + pics.get(i).getGcdm());
                    File file = new File("D:/szsh/sztp/" + pics.get(i).getGcdm() + File.separator + "营业执照" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();

                    //删除服务器上的临时文件
                    File deleteFile = new File(pics.get(i).getGcdm());
                    deleteFile.delete();
                }

                //食品经营许可证
                if (ToolUtil.isNotEmpty(pics.get(i).getFoodBusinessLicensePic())){
                    String spjyxkz = pics.get(i).getFoodBusinessLicensePic();
                    if (!spjyxkz.contains("http")){
                        spjyxkz = "https://rs.bantianyaozg.com" + spjyxkz;
                        //spjyxkz = "http://127.0.0.1:88" + spjyxkz;
//                        spjyxkz = "http://http://192.168.188.178:82" + spjyxkz;
                    }
                    if (spjyxkz.contains(" ")){
                        spjyxkz = spjyxkz.replaceAll(" ", "%20");
                    }
                    //根据图片地址构建URL
                    URL url = new URL(spjyxkz);//食品经营许可证
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/szsh/sztp/" + pics.get(i).getGcdm());//C:\Users\csh\Desktop
                    File file = new File("D:/szsh/sztp/" + pics.get(i).getGcdm() + File.separator + "食品经营许可证" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                //法人身份证
                if (ToolUtil.isNotEmpty(pics.get(i).getFrsfz())){
                    String frCards = pics.get(i).getFrsfz();
                    if (frCards.contains(",")){
                        int num = 1;
                        for (String frCard: frCards.split(",")) {

                            if (!frCard.contains("http")){
                                frCard = "https://rs.bantianyaozg.com" + frCard;
                                //frCard = "http://127.0.0.1:88" + frCard;

//                        frCard = "http://http://192.168.188.178:82" + frCard;
                            }
                            if (frCard.contains(" ")){
                                frCard = frCard.replaceAll(" ", "%20");
                            }
                            //根据图片地址构建URL
                            URL url = new URL(frCard);//食品经营许可证
                            URLConnection conn = url.openConnection();
                            conn.setReadTimeout(10000);
                            conn.setConnectTimeout(10000);
                            conn.connect();
                            DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                            //创建目录和图片
                            File pathFile = new File("D:/szsh/sztp/" + pics.get(i).getGcdm());//C:\Users\csh\Desktop
                            File file = new File("D:/szsh/sztp/" + pics.get(i).getGcdm() + File.separator + "法人身份证" + "(" + num + ")" + ".jpg");
                            if (!pathFile.exists()) {
                                pathFile.mkdirs();
                                file.createNewFile();
                            }
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            //通过流复制图片
                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = dataInputStream.read(buffer)) > 0) {
                                output.write(buffer, 0, length);
                            }
                            fileOutputStream.write(output.toByteArray());
                            dataInputStream.close();
                            fileOutputStream.close();
                            num++;
                        }
                    }else {
                        if (!frCards.contains("http")){
                            frCards = "https://rs.bantianyaozg.com" + frCards;
                            //frCards = "http://127.0.0.1:88" + frCards;
//                        frCard = "http://http://192.168.188.178:82" + frCard;
                        }
                        if (frCards.contains(" ")){
                            frCards = frCards.replaceAll(" ", "%20");
                        }
                        //根据图片地址构建URL
                        URL url = new URL(frCards);//食品经营许可证
                        URLConnection conn = url.openConnection();
                        conn.setReadTimeout(10000);
                        conn.setConnectTimeout(10000);
                        conn.connect();
                        DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                        //创建目录和图片
                        File pathFile = new File("D:/szsh/sztp/" + pics.get(i).getGcdm());//C:\Users\csh\Desktop
                        File file = new File("D:/szsh/sztp/" + pics.get(i).getGcdm() + File.separator + "法人身份证" + i + ".jpg");
                        if (!pathFile.exists()) {
                            pathFile.mkdirs();
                            file.createNewFile();
                        }
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        //通过流复制图片
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = dataInputStream.read(buffer)) > 0) {
                            output.write(buffer, 0, length);
                        }
                        fileOutputStream.write(output.toByteArray());
                        dataInputStream.close();
                        fileOutputStream.close();
                    }
                }

            }

            File file1 = new File("D:/szsh/sztp/");//创建文件目录的绝对路径
            if (!file1.exists()){
                file1.mkdir();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public LayuiPageInfo findPageReject() {
        Page pageContext = getPageContext();
        IPage page=baseMapper.selectPage(pageContext,new QueryWrapper<BtyDoubleCard>().eq("status",4).orderByDesc("create_time"));
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findPageSubmit() {
        Page pageContext = getPageContext();
        IPage page=baseMapper.selectPage(pageContext,new QueryWrapper<BtyDoubleCard>().eq("status",2).isNotNull("update_time"));
        return LayuiPageFactory.createPageInfo(page);
    }

    public static void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = file.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }

    private Serializable getKey(BtyDoubleCardParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyDoubleCard getOldEntity(BtyDoubleCardParam param) {
        return this.getById(getKey(param));
    }

    private BtyDoubleCard getEntity(BtyDoubleCardParam param) {
        BtyDoubleCard entity = new BtyDoubleCard();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
